package com.sms.utils;

import org.apache.commons.lang3.Validate;
import org.springframework.context.ApplicationContext;

/**
 * @desc 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
 * @author WuJiangWu
 * @date 2018年7月15日
 */
public class SpringContextHolder{

	private static ApplicationContext ctx = null;

	
	public static ApplicationContext getCtx() {
		assertContextInjected();
		return ctx;
	}
	public static void setCtx(ApplicationContext ctx) {
		SpringContextHolder.ctx = ctx;
	}

	/**
	 * 从静态变量applicationContext中取得Bean
	 * @param name
	 * @return T
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		assertContextInjected();
		return (T) ctx.getBean(name);
	}

	/**
	 * 从静态变量applicationContext中取得Bean
	 * @param class<T>
	 * @return T
	 */
	public static <T> T getBean(Class<T> requiredType) {
		assertContextInjected();
		return ctx.getBean(requiredType);
	}

	/** 检查ApplicationContext不为空. */
	private static void assertContextInjected() {
		Validate.validState(ctx != null, "act属性未注入,检测初始化环境");
	}
}